package no.uia.IKT508.XH;

import java.util.Timer;
import java.util.TimerTask;

import org.alljoyn.bus.BusException;

import android.R.bool;
import android.app.Activity;
import android.content.Context;
import android.media.AudioManager;
import android.media.AudioRecord;
import android.media.AudioTrack;
import android.media.MediaRecorder;
import android.util.Log;
import android.widget.Toast;

public class XHAudio extends Activity{
	
	private AudioManager mAudioManager;
	private AudioRecord mAudioRecord;
	private AudioTrack mAudioTrack;

	//the record buffer size
	private int recBufSize;
	
	//the buffer size of player
	private int playBufSize;
	
	//show if the audio has started
	private boolean hasStarted = false;
	
	//the timer which sends audio buffer periodically
	private Timer timer;
	
	//the store buffer
	private byte[] storeBuffer;
	
	public void Init()
	{
		
		recBufSize = AudioRecord.getMinBufferSize(XHVariable.frequency,  
				XHVariable.channelConfiguration, XHVariable.audioEncoding);  
 
        playBufSize=AudioTrack.getMinBufferSize(XHVariable.frequency,  
        		XHVariable.channelConfiguration, XHVariable.audioEncoding);
        
        //record
        mAudioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, XHVariable.frequency,  
        		XHVariable.channelConfiguration, XHVariable.audioEncoding, recBufSize);  
 
        //play
        mAudioTrack = new AudioTrack(AudioManager.STREAM_VOICE_CALL, XHVariable.frequency,  
        		XHVariable.channelConfiguration, XHVariable.audioEncoding,  
                playBufSize, AudioTrack.MODE_STREAM); 
        
//        mAudioManager = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
//        
//        mAudioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL, mAudioManager.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL), 0);
        
        mAudioTrack.setStereoVolume(0.7f, 0.7f);
	}
	
	
	//set the volumn
	public void setAudioTrack(float leftVolumn, float rightVolumn)
	{
		mAudioTrack.setStereoVolume(leftVolumn, rightVolumn);
	}
	
	//modify the tag if it has started
	public void modifyAudio(boolean value)
	{
		this.hasStarted = value;
	}
	
	//inform the client to start
	public void startPlay(boolean value) throws BusException
	{
		if (true == value)
		{
			//the record buffer
	        storeBuffer = new byte[recBufSize];
	        
	        //start the audio track
	        mAudioTrack.play();
		}
		
		this.hasStarted = value;
	}
	
	//play the sound from the remote device
	public void startRecord()
	{
		//record sound from the device
        mAudioRecord.startRecording();
        
	}
	
	//start record the sound from the device
	public void runAudio()
	{
		new RecordPlayThread().start();
	}
	
	//on the process
	public void audioOnProcess(byte[] playBuffer, int size)
	{
		mAudioTrack.write(playBuffer, 0, size);
		
	}
	
	class RecordPlayThread extends Thread {  
        public void run() {  
            try {  
                timer = new Timer();
                
                //execute the audio task every 100ms
                //transmit the sound buffer to the timertask
                timer.schedule(new AudioTask(storeBuffer), 0, XHVariable.timerDelay);
                	
            } catch (Throwable t) {  
                Toast.makeText(XHAudio.this, t.getMessage(), 1000);  
            }  
        }
    };  
    
    class AudioTask extends TimerTask
    {
    	private byte[] buffer;
    	
    	//get the buffer from the constructor function
    	public AudioTask(byte[] soundBuffer)
    	{
    		this.buffer = soundBuffer;
    	}

		@Override
		public void run() {
			//recording
			if (true == hasStarted)
			{
				try
	        	{
					//what's the meaning of this code
					//get the record sound from the buffer
	                int bufferReadResult = mAudioRecord.read(buffer, 0,  
	                        recBufSize);  
	                
	                //send the sound buffer to the remote client
	                XHChat.mService.startAudio(buffer, bufferReadResult);
	        	}
	        	catch (Exception e)
	        	{
	        		e.printStackTrace();
	        	}
			}
			else
			{
				timer.cancel();
				//stop
		        mAudioRecord.stop();
		        mAudioTrack.stop();
			}
		}
    }
}